define(["core", "coAjax", "dataAnimate", "hash_routie", "Locker"], function(jSouper, coAjax, dataAnimate, hash_routie, Locker) {

	var GOODS_ARGS_MAP_TYPE_array = [];
	var _card_factory_id;
	jSouper.forEach(appConfig.GOODS_ARGS_MAP_TYPE, function(value, key) {
		GOODS_ARGS_MAP_TYPE_array.push({
			key: key,
			value: value
		});
	});
	App.set("$Cache.GOODS_ARGS_MAP_TYPE_array", GOODS_ARGS_MAP_TYPE_array);


	App.set("$Event.tag.add_new_tag", function() {
		var new_tag_name = jSouper.trim(App.get("$Cache.tag.new_tag_name"));
		if (new_tag_name) {
			coAjax.post(appConfig.bus.add_tag, {
				tag_name: new_tag_name
			}, function(result) {
				App.model.push("$Cache.shelves.bus_tags", result.result);
			});
		}
	});
	App.set("$Event.tag.use_tag", function(e, vm) {
		vm.set("_checked", true);
	});
	App.set("$Event.tag.unuse_tag", function(e, vm) {
		vm.set("_checked", false);
	});

	//图片批量上传
	App.set("$Event.mul_img_upload.cb", function(e) {
		var imgs_info = App.get("$Cache.mul_img_upload.imgs");
		App.set("$Cache.mul_img_upload.info", "");
		_init_detail_imgs(imgs_info);
	});
	//图片批量上传的处理
	App.set("$Event.mul_img_upload.hp_cb", dataAnimate(function hp_cb(percentage) {
		// console.log("handle", percentage)
		if (percentage >= 1) {
			hp_cb.dataAnimateReset();
			App.set("$Cache.mul_img_upload.info", "图片上传中……");
		} else {
			App.set("$Cache.mul_img_upload.info", "图片处理中：" + (percentage * 100).toFixed(2) + "%")
		}
	}, 5));
	App.set("$Event.mul_img_upload.err_cb", function() {
		App.set("$Cache.mul_img_upload.info", "上传失败，点击重新进行批量上传");
	});
	App.set("$Event.mul_img_upload.up_cb", dataAnimate(function up_cb(percentage) {
		App.get("$Event.mul_img_upload.hp_cb").dataAnimateStop();
		// console.log("upload", percentage)
		if (percentage >= 1) {
			up_cb.dataAnimateReset();
			App.set("$Cache.mul_img_upload.info", "图片上传完成，服务器正在处理数据……");
		} else {
			App.set("$Cache.mul_img_upload.info", "图片处理完成，上传中：" + (percentage * 100).toFixed(2) + "%");
		}
	}, 50));
	App.set("$Event.goods_detail.on_card_factory_list_change", function() {
		var new_card_factory_id = App.get("$Cache.new_goods.card_factory_list.0") || "";
		if (new_card_factory_id !== _card_factory_id) {
			_card_factory_id = new_card_factory_id;
			//标签列表要显示或隐藏（直接通过class绑定实现）
			//商品类目表要变
			_init_goods_classify(_card_factory_id);
			//删除已经选择的类目
			if (App.get("$Cache.new_goods.classify_id")) {
				App.set("$Cache.new_goods.classify_id", "");
				alert("warn", "您修改了商品所属专区，请重新选择商品类目（点击关闭提示）", 1000000);
			}
		}
	});

	App.set("$Event.goods_args_map.add_arg", function _add_arg() {
		if (!App.get("$Cache.new_goods.goods_args_map")) {
			coAjax.post(appConfig.bus.goods_args_map_add, {
				goods_arg_array: [{
					goods_id: App.get("$Cache.new_goods._id")
				}]
			}, function(result) {
				goods_args_map = result.result
				App.set("$Cache.new_goods.goods_args_map_id", goods_args_map._id);
				App.set("$Cache.new_goods.goods_args_map", goods_args_map);
				_add_arg();
			});
			return
		}
		var args = App.get("$Cache.new_goods.goods_args_map.info.args");
		args.push({
			title: "",
			items: []
		});
		App.set("$Cache.new_goods.goods_args_map.info.args", args);
	});

	App.set("$Event.goods_args_map.add_goods_args_map_item", function(e, vm) {
		vm.push("items", vm.get("_new_goods_args_map"))
		vm.set("_new_goods_args_map", {});
		App.get("$Event.goods_args_map.upload")();
	});
	App.set("$Event.goods_args_map.update_goods_args_map_item", function(e, vm) {
		App.get("$Event.goods_args_map.upload")();
	});
	App.set("$Event.goods_args_map.remove_goods_args_map_item", function(e, vm) {
		var items = vm.get("items");
		items.splice(items.indexOf(vm.get()), 1);
		vm.set("items", items);
	});
	App.set("$Event.goods_args_map.cancel_update_goods_args_map_item", function(e, vm) {
		vm.set("_new_goods_args_map", {});
	});
	App.set("$Event.goods_args_map.edit_goods_args_map_item", function(e, vm) {
		vm.set("$Caller._new_goods_args_map", vm.get());
	});
	App.set("$Event.goods_args_map.upload", function() {
		_upload_goods_args_map(App.get("$Cache.new_goods"));
	});
	App.set("$Event.goods_args_map.remove", function(e, vm) {
		myConfirm("确定要删除这个可选属性吗?", function() {
			var goods_args_map_args = App.get("$Cache.new_goods.goods_args_map.info.args");
			goods_args_map_args.splice(goods_args_map_args.indexOf(vm.get()), 1);
			_upload_goods_args_map(App.get("$Cache.new_goods"));
		});
	});

	//添加同类商品
	App.set("$Event.some_goods_args_goods_list.add", function() {
		//复制一份当前编辑的商品的数据
		var new_goods = JSON.parse(JSON.stringify(App.get("$Cache.new_goods")));
		new_goods.using_goods_args = [];
		new_goods._id = null;
		//提交这份数据，不存储在store中。
		_upload_goods("new -no_store", function(new_goods) {
			App.push("$Cache.some_goods_args_goods_list", new_goods);
			// App.push("$Cache.some_goods_args_goods_list", new_goods);
		});
	});
	//编辑同类商品
	App.set("$Event.some_goods_args_goods_list.edit_current_goods", function(e, vm) {
		hash_routie.hash({
			"id": vm.get("_id")
		});
	});
	//hover显示更多信息
	App.set("$Event.some_goods_args_goods_list.show_more", function(e, vm) {
		vm.set("$Private.show_more", true)
	});
	App.set("$Event.some_goods_args_goods_list.hidden_more", function(e, vm) {
		vm.set("$Private.show_more", false)
	});

	//检查数据状态，完成后上传
	function _check_and_upload_goods(type) {
		//默认，使用新建
		if (type !== "update") {
			var _lock = _lock_post;
			var _unlock = _unlock_post;
		} else {
			_lock = _lock_put;
			_unlock = _unlock_put;
		}
		//锁定提交按钮，避免再次提交
		_lock();
		//封面
		var preview_img_url = App.get("$Cache.new_goods.preview_img_url");
		//校验相关数据
		if (!preview_img_url) {
			//如果在上传中，等待上传完成
			if (App.get("$Cache.shelves.preview_img_url_upload_status")) {
				alert("warn", "请等待商品封面图片上传完成");
				_unlock();
			} else {
				alert("warn", "请上传商品封面图片");
				_unlock();
			}
			return;
		}
		//详情图
		var _detail_img_urls = App.get("$Cache.shelves.detail_img_urls");
		var _warn_str;
		_detail_img_urls.forEach(function(detail_img) {
			if (detail_img.status) {
				_warn_str = "请等待商品详情图上传完成";
			}
		});
		if (_warn_str) {
			alert("warn", _warn_str);
			_unlock();
			return;
		}
		//商品详情
		if (App.get("$Cache.shelves.goods_detail_content_img_upload_status")) {
			alert("warn", "请等待商品详细介绍中的图片上传完成");
			_unlock();
			return;
		}


		//检查通过，上传商品
		_upload_goods(type);
	};

	//正式上传
	function _upload_goods(type, cb) {
		var new_goods_info = App.get("$Cache.new_goods");
		var tags = [];
		//提取选中的tags
		var bus_tags = App.get("$Cache.shelves.bus_tags") || [];
		bus_tags.forEach(function(tag) {
			if (tag._checked) {
				tags.push(tag._id);
			}
		});
		new_goods_info.tags = tags;
		//提取有效的详情图
		var _detail_img_urls = App.get("$Cache.shelves.detail_img_urls");
		var detail_img_urls = [];
		_detail_img_urls.forEach(function(detail_img) {
			if (detail_img && detail_img.url) {
				detail_img_urls.push(detail_img.url);
			}
		});
		new_goods_info.detail_img_urls = detail_img_urls;

		//商品所属专区
		var card_factory_id = new_goods_info.card_factory_list && new_goods_info.card_factory_list[0];
		//新增模式，默认
		if (type && type.indexOf("update") !== 0) {
			if (card_factory_id) {
				var url = appConfig.bus.card_factory_add_goods + card_factory_id
			} else {
				url = appConfig.bus.post_goods;
			}
			if (type.indexOf("-no_store") !== -1) {
				new_goods_info.no_store = true
			} else {
				delete new_goods_info.no_store;
			}
			coAjax.post(url, new_goods_info, function(result) {
				// App.set("$Cache.shelves.upload_info","商品添加成功");
				alert("success", "商品添加成功");
				//执行回调，也可操作商品分类信息，下一步就要提交修改了
				cb ? cb(result.result) : _init();
				//修改商品分类信息
				type.indexOf("-no_update_goods_args_map") === -1 && _upload_goods_args_map(result.result);
				//解锁提交按钮，清空表单
				_unlock_post();
			}, function(errorCode, xhr, errorMsg) {
				switch (errorCode) {
					case "00068":
						alert("error", "还未输入“标题”");
						break;
					case "00012":
						alert("error", "请先填写表单");
						break;
				}
				alert("error", errorMsg)
				_unlock_post();
			});
		} else { //修改模式
			if (card_factory_id) {
				url = appConfig.bus.card_factory_update_goods + card_factory_id
			} else {
				url = appConfig.bus.put_goods;
			}
			coAjax.put(url, new_goods_info, function(result) {
				// App.set("$Cache.shelves.upload_info","商品添加成功");

				alert("success", "商品修改成功");
				//执行回调，也可操作商品分类信息，下一步就要提交修改了
				cb ? cb(result.result) : _init(result.result);
				//修改商品分类信息
				type.indexOf("-no_update_goods_args_map") === -1 && _upload_goods_args_map(result.result);
				//解锁提交按钮，清空表单
				_unlock_put();
			}, function(errorCode, xhr, errorMsg) {
				switch (errorCode) {
					case "00068":
						alert("error", "还未输入“标题”");
						break;
					case "00012":
						alert("error", "请先填写表单");
						break;
				}
				alert("error", errorMsg)
				_unlock_put();
			});
		}
	};

	//可选属性
	function _upload_goods_args_map(new_goods_info, cb) {
		//商品必须已经提交，在非新增模式下才能操作
		//修改模式，必须是修改模式，新增模式必须在商品上传前就有
		if (new_goods_info.goods_args_map_id) {
			var goods_args_map_info = new_goods_info.goods_args_map.info;

			var goods_arg_array = goods_args_map_info.goods_arg_array = jSouper.map(App.get("$Cache.some_goods_args_goods_list"), function(goods) {
				return {
					goods_id: goods._id
				}
			});

			//添加当前的商品
			var no_current_goods = true;
			jSouper.forEach(goods_arg_array, function(goods_arg_info) {
				return no_current_goods = !(goods_arg_info.goods_id == new_goods_info._id)
			});
			if (no_current_goods) {
				goods_arg_array.push({
					goods_id: new_goods_info._id
				});
			}

			coAjax.put(appConfig.bus.goods_args_map_update + new_goods_info.goods_args_map_id, {
				info: goods_args_map_info
			}, function(result) {
				alert("success", "可选属性修改成功");
				cb && cb(result.result);
				App.set("$Cache.new_goods.goods_args_map", result.result);
			});
		}
	}
	//锁定添加，放置连续点击
	function _lock_post() {
		alert("info", "新商品创建中")
		App.set("$Cache.shelves.upload_info", "新商品创建中");
		App.set("$Cache.shelves.lock_submit_button", true);
	};

	function _unlock_post() {
		App.set("$Cache.shelves.upload_info", "");
		App.set("$Cache.shelves.lock_submit_button", false);
	};
	//修改商品
	function _lock_put() {
		alert("info", "商品修改中")
		App.set("$Cache.shelves.upload_info", "商品修改中");
		App.set("$Cache.shelves.lock_submit_button", true);
	}

	function _unlock_put() {
		App.set("$Cache.shelves.upload_info", "");
		App.set("$Cache.shelves.lock_submit_button", false);
	};
	//初始化商品
	function _init(goods_to_update) {
		goods_to_update || (goods_to_update = {});

		App.set("$Cache.new_goods", goods_to_update);
		//反向绑定标签
		coAjax.get(appConfig.bus.tags, {
			bus_id: busInfo._id
		}, function(result) {
			_init_goods_tags(goods_to_update.tags, result.result);
		});
		//反向绑定详情图片
		_init_detail_imgs(goods_to_update.detail_img_urls);
		//运费模板
		coAjax.get(appConfig.bus.express_list, function(result) {
			_init_bus_express(result.result)
		});
		//商品所属专区
		coAjax.get(appConfig.bus.card_factory_list, function(result) {
			_init_bus_card_factory(result.result, goods_to_update)
		});
		//商品可选属性
		_init_goods_args_map(goods_to_update);
		//商品类目
		_card_factory_id = App.get("$Cache.new_goods.card_factory_list.0") || "";
		_init_goods_classify(_card_factory_id);
	};

	function _init_goods_tags(goods_tags, bus_tags) {
		var tags_map = {};
		goods_tags || (goods_tags = []);
		for (var i = 0, tag; tag = goods_tags[i]; i += 1) {
			tags_map[tag] = true;
		}
		for (var i = 0, tag; tag = bus_tags[i]; i += 1) {
			if (tags_map[tag._id]) {
				tag._checked = true;
			}
		}
		App.set("$Cache.shelves.bus_tags", bus_tags);
	}

	function _init_detail_imgs(detail_img_urls) {
		var _detail_img_urls = Array(appConfig.server_config.storeImagesNumber);
		if (detail_img_urls) {
			for (var i = 0, len = detail_img_urls.length, url; url = detail_img_urls[i]; i += 1) {
				_detail_img_urls[i] = {
					url: url
				}
			}
		}
		App.set("$Cache.shelves.detail_img_urls", _detail_img_urls)
	}

	function _init_bus_express(express_list) {
		express_list.unshift({
			_id: "",
			name: "商家承担运费",
			express_price: 0
		});
		App.set("$Cache.bus.goods_detail.express_list", express_list)
	}

	function _init_bus_card_factory(card_factory_list, goods_to_update) {
		//如果是修改模式，不可选用
		if (goods_to_update._id) {
			var card_factory_id = goods_to_update.card_factory_list && goods_to_update.card_factory_list[0];
			if (card_factory_id) {
				jSouper.forEach(card_factory_list, function(card_factory) {
					if (card_factory._id == card_factory_id) {
						App.set("$Cache.bus.selected_card_factory", card_factory)
						return false
					}
				});
			}
		}
		card_factory_list.unshift({
			_id: "",
			info: {
				name: "(无专区)"
			}
		})
		App.set("$Cache.bus.goods_detail.card_factory_list", card_factory_list)
	};

	function _init_goods_args_map(goods_to_update) {
		if (goods_to_update.goods_args_map) {
			goods_arg_array = goods_to_update.goods_args_map.info.goods_arg_array || [];
			var goods_id_list = jSouper.map(goods_arg_array, function(goods_arg_info) {
				return goods_arg_info.goods_id
			});
			goods_id_list.length ? coAjax.get(appConfig.goods.byIds, {
				goods_id_list: goods_id_list
			}, function(result) {
				App.set("$Cache.some_goods_args_goods_list", result.result)
			}) : App.set("$Cache.some_goods_args_goods_list", []);
		} else {
			App.set("$Cache.some_goods_args_goods_list", [])
		}
	};

	function _init_goods_classify(card_factory_id) {
		card_factory_id = null; //现在商品全部放到主目录里面
		if (card_factory_id) {
			var classify_tree = appConfig.bus.c_f_c.classify_tree.replace(":card_factory_id", card_factory_id);
		} else {
			classify_tree = appConfig.bus.classify_tree;
		}
		coAjax.get(classify_tree, function(result) {
			App.set("$Cache.goods_detail.classify_tree", result.result);
		});
	};

	return {
		init: _init,
		upload_goods: _check_and_upload_goods,
		lock_post: _lock_post,
		unlock_post: _unlock_post,
		lock_put: _lock_put,
		unlock_put: _unlock_put
	}
});